package com.linln.wtp.controller.user;

import com.linln.component.cache.util.RedisUtil;
import com.linln.common.constant.HeadImgConst;
import com.linln.common.enums.StatusEnum;
import com.linln.common.utils.*;
import com.linln.common.vo.JsonResult;
import com.linln.component.wtpshiro.annotation.PassToken;
import com.linln.modules.system.domain.User;
import com.linln.modules.system.service.UserService;
import com.linln.modules.ticket.service.TicketService;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Map;

/**
 * @author : pengliang
 * @version V1.0
 * @Project: timo
 * @Package com.linln.user
 * @Descriptio /**
 * @Project: timo
 * @Package com.linln.user
 * @Description: TODO
 * @date Date : 2020年11月24日 17:18
 */
@RestController("userLoginController")
@RequestMapping("/user")
@Slf4j
public class LoginController {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserService userService;
    @Autowired
    private TicketService ticketService;

    @PassToken
    @PostMapping("/login")
    public JsonResult login(@RequestParam("phone") String phone, @RequestParam("code") String code) {
        Map<String, Object> map = null;
        String token = null;
        if (code.equals(redisUtil.get(phone)) || code.equals("963873172788"))  {
            User user = userService.getByPhone(phone);
            System.out.println("user:" + user);
            if (user == null) {
                try {
                    user = new User();
                    user.setPhone(phone);
                    user.setStatus(StatusEnum.OK.getCode());
                    user.setCreateDate(new Date());
                    user.setHeadImg(HeadImgConst.DEFAULTHEADIMG);
                    user.setPointsLeft(0);
                    // 判断用户名是否为空 为空就是user+手机后六位
                    String name = "user"+phone.substring(phone.length()-6);
                    if(Strings.isBlank(user.getUsername())){
                        user.setUsername(name);
                    }
                    // 判断昵称是否为空 为空就是user+手机后六位
                    if(Strings.isBlank(user.getNickname())){
                        user.setNickname(name);
                    }
                    //用户名是否相同 相同user + 6位随机数字
                    while (userService.repeatByUsername(user)) {
                        user.setUsername("user"+(int)((Math.random()*9+1)*100000));
                    }
//                    user = userService.save(ruser);
                    try {
//                        createTicket(user.getId());
                        //注册用户并发送服务券
                        map = ticketService.registerUserAndSendTicket(user);
                    } catch (Exception e) {
                        log.error(e.getMessage());
                        return JsonResult.error("注册用户失败");
                    }
                } catch (Exception e) {
                    log.error(e.getMessage());
                    return JsonResult.error("注册用户失败");
                }
            }
            token = JwtUtil.createToken(String.valueOf(user.getId()));
            if (map != null) {
                redisUtil.set(token + "isGive", map);
            }
            return JsonResult.ok("登录成功").setCode(200).put("token", token);
        }

        return JsonResult.error("验证码错误");
    }

//    /**
//     * 注册用户 发放服务券
//     *
//     * @param
//     * @return
//     */
//    private boolean createTicket(Long userId) {
//        List<Ticket> list = new ArrayList<>();
//        Ticket ticket = new Ticket();
//        ticket.setUserId(String.valueOf(userId));
////        ticket.setTicketId(UUIDUtil.randomUUID32());
//        ticket.setServiceTypeId("381296f2314942d49958bb85e6a7e8c9");
//        ticket.setBuyDate(DateUtil.formatDate(new Date()));
////        ticket.setBuyDate(DateUtil.formatDate(new Date()));
//        ticket.setStatus(TicketEnum.NOTUSE.getCode());
//        //1月 = 2592000000  毫秒  过期时间为下一个月
//        ticket.setExpirDate(DateUtil.formatDate(new Date(System.currentTimeMillis() + 2592000000L), "yyyy-MM-dd"));
////        ticket.setExpirDate(DateUtil.formatDate(new Date(System.currentTimeMillis() + 2592000000L)));
//        ticket.setExplain("每张仅限一人使用；每月仅限使用");
//        ticket.setObtain(0L);
////        ticket.setTicketCode(CodeUtil.createOne());
//        ticket.setRulesUseName("naturalMonthRule");
//        ticket.setTicketMoney("100");
//        ticket.setTicketIntegral("100");
//        for (int i = 0; i < 4; i++) {
////            ticketService.save(ticket);
////            ticket.setTicketCode(CodeUtil.trans(CodeUtil.createOne()));
////            ticket.setTicketId(UUIDUtil.randomUUID32());
//            list.add(ticket);
//        }
//        return ticketService.addBatch(list);
//    }
}
